package com.qf.security;

import com.alibaba.fastjson.JSONObject;
import com.qf.entity.TlPerm;
import com.qf.utils.*;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.util.StringUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

public class QfBasicAuthenticationFilter extends BasicAuthenticationFilter {
    AuthenticationManager authenticationManager;//认证管理器
    RedisTemplate redisTemplate;

    public QfBasicAuthenticationFilter(AuthenticationManager authenticationManager, RedisTemplate redisTemplate){
        super(authenticationManager);//父类有参构造需要的参数--
        this.authenticationManager=authenticationManager;
        this.redisTemplate=redisTemplate;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        //请求头部信息--jwt--获得当前用户信息
        String uuid=request.getHeader("token");
        if (uuid!=null) {
            if (!StringUtils.isEmpty(uuid)) {
                String jwt = (String) redisTemplate.boundValueOps(RedisKey.LOGIN_USER + uuid).get();
                List<String> list = TokenTools.getNamePass(jwt);

                //redis权限存储在redis中--LOGIN_ADMIN_PERM--list
                //取出所有权限
                List range = redisTemplate.opsForList().range(RedisKey.LOGIN_ADMIN_PERM, 0, -1);
                //JSONObject.parseObject(JSONObject.toJSONString(range),)
                List<TlPerm> tbPermissions = JSONObject.parseArray(JSONObject.toJSONString(range), TlPerm.class);
                //将权限存储在权限上下文对象中
                UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(list.get(0), list.get(1), AuthorityUtils.commaSeparatedStringToAuthorityList(tbPermissions.stream().map(p -> p.getPermId().toString()).collect(Collectors.joining(","))));
                SecurityContextHolder.getContext().setAuthentication(token);
            }
        }
        //放行
        chain.doFilter(request,response);
//        super.doFilterInternal(request, response, chain);
    }


}
